package com.shushan.lockscreen;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.common.ui.OnRecyclerviewItemClickListener;
import com.android.xrecyclerview.ProgressStyle;
import com.android.xrecyclerview.XRecyclerView;
import com.shushan.base.Constants;
import com.shushan.home.TabHomeActivity;
import com.shushan.lockscreen.bean.AppInfo;
import com.shushan.service.ForegroundRTAService;
import com.shushan.shushanbao.R;
import com.shushan.util.ControlUtil;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToastUtils;
import com.shushan.util.ToolUtils;
import java.util.List;


/**
 * @ClassName: GamesFloatWindow
 * @Desciption: 允许小孩使用的应用界面
 * @author: yichaohua
 * @date: 2018-06-04
 */
public class GamesFloatWindow extends LinearLayout implements View.OnClickListener, OnRecyclerviewItemClickListener, XRecyclerView.LoadingListener {

    private static final String TAG = "GamesFloatWindow";

    private Context mContext;
    private XRecyclerView gamesRecyclerView;
    private ImageView leftBackImg;
    private GamesAdapter gamesAdapter;
    private RelativeLayout quitDialogLayout;
    private RelativeLayout cancelLayout,okDialogLayout;

    private int paperId = 0;

    public GamesFloatWindow(Context mContext) {
        super(mContext);
        this.mContext = mContext;

        LayoutInflater.from(mContext).inflate(R.layout.games_float_window, this);

        initView();
    }


    private void initView() {
        leftBackImg = findViewById(R.id.actionbar_left_back_img);
        leftBackImg.setOnClickListener(this);
        gamesRecyclerView = findViewById(R.id.games_float_rv);
        //设置RecyclerView 布局
        gamesRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        gamesRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        gamesRecyclerView.setArrowImageView(R.drawable.refresh_down_arrow);
        gamesRecyclerView.getDefaultRefreshHeaderView().setRefreshTimeVisible(true);
        gamesRecyclerView.setLoadingMoreEnabled(false);
        gamesRecyclerView.setLoadingListener(this);

        gamesAdapter = new GamesAdapter();
        gamesAdapter.setRecyclerviewItemClickListener(this);
        gamesRecyclerView.setAdapter(gamesAdapter);
        gamesRecyclerView.refresh();

        quitDialogLayout = findViewById(R.id.games_float_dialog_layout);
        cancelLayout = findViewById(R.id.games_float_dialog_cancel_layout);
        cancelLayout.setOnClickListener(this);
        okDialogLayout = findViewById(R.id.games_float_dialog_ok_layout);
        okDialogLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.actionbar_left_back_img:
                quitDialogLayout.setVisibility(VISIBLE);
                break;
            case R.id.games_float_dialog_cancel_layout:
                quitDialogLayout.setVisibility(GONE);
                break;
            case R.id.games_float_dialog_ok_layout:
                quitGames();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClickListener(View v, int position) {
        List<AppInfo> appInfoList = gamesAdapter.getAppInfoList();
        if(!ToolUtils.isListEmpty(appInfoList)){
            AppInfo appInfo = appInfoList.get(position);
            if(appInfo != null){
                SystemUtils.startApp(mContext,appInfo.getPackageName());
                GamesWindowManager.removeGamesFloatWindow(mContext);

                Intent intent = new Intent(mContext,ForegroundRTAService.class);
                intent.putExtra("paperId",paperId);
                intent.putExtra("allowPackName",appInfo.getPackageName());
                intent.putExtra("allowAppLabel",appInfo.getLabel());

                mContext.startService(intent);
            }
        }
    }

    private void quitGames() {
        quitDialogLayout.setVisibility(GONE);

        Intent intent = new Intent(mContext,TabHomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);

        Intent intent1 = new Intent(mContext,ForegroundRTAService.class);
        mContext.stopService(intent1);

        ToolUtils.cancelLockAlarm(mContext);

        GamesWindowManager.removeGamesFloatWindow(mContext);

        long startTime = SharedPreferencesUtils.getLongDate(Constants.START_GAME_TIME_SHAREPREFERS_KEY);
        long currentTime = System.currentTimeMillis();
        int min = (int) ((currentTime - startTime)/(1000 * 60));
        Log.i(TAG,"min=" + min);
        if(min > 0){
            ControlUtil.delGameTime(min);
        }
    }

    public void setQutiGone(){
        if(quitDialogLayout != null){
            quitDialogLayout.setVisibility(GONE);
        }
    }

    @Override
    public void onRefresh() {
        Log.i(TAG,"onRefresh()");

        new GetAppListTask().execute();
    }

    @Override
    public void onLoadMore() {

    }

    private class GamesAdapter extends  RecyclerView.Adapter<GamesAdapter.ViewHolder> implements OnClickListener {

        private List<AppInfo> appInfoList;
        private OnRecyclerviewItemClickListener recyclerviewItemClickListener;


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.games_list_item, null, false);
            view.setOnClickListener(this);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if(appInfoList != null){
                AppInfo appInfo = appInfoList.get(position);

                Drawable logo = appInfo.getIcon();
                holder.imageView.setImageDrawable(logo);
                holder.textView.setText(appInfo.getLabel());
                holder.itemView.setTag(position);//给view设置tag以作为参数传递到监听回调方法中
            }
        }

        @Override
        public int getItemCount() {
            if(appInfoList == null){
                return 0;
            }else{
                return appInfoList.size();
            }

        }

        public void setRecyclerviewItemClickListener(OnRecyclerviewItemClickListener recyclerviewItemClickListener) {
            this.recyclerviewItemClickListener = recyclerviewItemClickListener;
        }

        @Override
        public void onClick(View v) {
            if(recyclerviewItemClickListener != null){
                recyclerviewItemClickListener.onItemClickListener(v, ((int) v.getTag()));
            }
        }

        public List<AppInfo> getAppInfoList() {
            return appInfoList;
        }

        public void setAppInfoList(List<AppInfo> appInfoList) {
            this.appInfoList = appInfoList;
        }

        class ViewHolder extends RecyclerView.ViewHolder{
            private ImageView imageView;
            private TextView textView;

            public ViewHolder(View itemView) {
                super(itemView);

                imageView = itemView.findViewById(R.id.games_list_item_img);
                textView = itemView.findViewById(R.id.games_list_item_tv);
            }
        }
    }

    public int getPaperId() {
        return paperId;
    }

    public void setPaperId(int paperId) {
        this.paperId = paperId;
    }

    private class GetAppListTask extends AsyncTask<Void,Void,List<AppInfo>>{

        @Override
        protected List<AppInfo> doInBackground(Void... voids) {
            List<AppInfo> appInfoList = SystemUtils.getAllowUsePackages(mContext);
            return appInfoList;
        }

        @Override
        protected void onPostExecute(List<AppInfo> appInfoList) {
            if(ToolUtils.isListEmpty(appInfoList)){
                ToastUtils.showToast(mContext,"获取的应用列表为空");
                return;
            }

            gamesAdapter.setAppInfoList(appInfoList);
            gamesAdapter.notifyDataSetChanged();
            if(gamesRecyclerView != null){
                gamesRecyclerView.refreshComplete();
            }
        }
    }
}
